package com.example.security.service;

import cn.hutool.core.lang.UUID;
import com.example.core.constants.CacheConstants;
import com.example.core.constants.JwtConstants;
import com.example.redis.service.RedisService;
import com.example.core.domain.LoginUser;
import com.example.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lily
 * Date: 2024-11-23
 * Time: 18:56
 */
@Service
@Slf4j
public class TokenService {


    @Autowired
    private RedisService redisService;

    /**
     * 创建Token
     * @param userId
     * @param secret
     * @param identity
     * @param nickname
     * @return
     */
    public String createToken(Long userId, String secret, Integer identity,String nickname,String headImg) {

        Map<String, Object> claims = new HashMap<>();
        //UUID来保证唯一性
        String userKey = UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID, userId);
        claims.put(JwtConstants.LOGIN_USER_KEY, userKey);
        //用户信息和盐值
        String token = JwtUtils.createToken(claims, secret);

        //redis的建
        String key = getTokenKey(userKey);
        //redis的值
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickname);
        loginUser.setHeadImage(headImg);
        //存入token
        redisService.setCacheObject(key, loginUser, CacheConstants.EXP, TimeUnit.MINUTES);
        return token;
    }

    /**
     * 延长redis当中从存储的用于用户身份认证的敏感信息的有效时间
     */
    public void extendToken(String token, String secret) {
        /*if(StringUtils.isBlank(token)) {
            return;
        }*/
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return;
        }
        //获取对应的redis中的建
        String tokenKey = getTokenKey(userKey);
        //延长redis当中的有效时间
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire != null && expire < CacheConstants.REFRESH_TIME) {
            redisService.expire(tokenKey, CacheConstants.EXP, TimeUnit.MINUTES);
        }
    }

    private String getTokenKey(String userKey) {

        return CacheConstants.LOGIN_TOKEN_KEY + userKey;
    }

    public LoginUser getLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return null;
        }
        return redisService.getCacheObject(getTokenKey(userKey),LoginUser.class);
    }

    public boolean deleteLoginUser(String token, String secret) {

        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));
    }

    public Long getUserId(Claims claims) {
        if (claims == null) return null;
        return Long.valueOf(JwtUtils.getUserId(claims));  //获取jwt中的key
    }

    public String getUserKey(Claims claims) {
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);  //获取jwt中的key
    }

    private String getUserKey(String token, String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);  //获取jwt中的key
    }

    public Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息
            if (claims == null) {
                log.error("解析token：{}, 出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token：{}, 出现异常", token, e);
            return null;
        }
        return claims;
    }

    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        String tokenKey = getTokenKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }

}
